﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace CommonClasses.Utility
{
    /// <summary>
    /// Инструменты и расширения для коллекций
    /// </summary>
    public static class CollectionsUtility
    {
        /// <summary>
        /// Преобразовать содержимое данного Dictionary
        /// </summary>
        /// <typeparam name="TKey">Тип ключа</typeparam>
        /// <typeparam name="TValue">тип значения</typeparam>
        /// <returns>Dictionary с преобразованным содержимым</returns>
        public static Dictionary<TKey, TValue> Cast<TKey, TValue>(this IDictionary<TKey, TValue> This)
        {
            Dictionary<TKey, TValue> res = new Dictionary<TKey, TValue>();
            foreach (var k in This.Keys)
                res.Add((TKey)k, (TValue)This[k]);
            return res;
        }

        public static T Find<T>(this IList<T> list, Predicate<T> predicate)
        {
            foreach (var item in list)
                if (predicate(item)) return item;

            return default(T);
        }


        public static object Find(this IList list, Predicate<object> predicate)
        {
            foreach (var item in list)
                if (predicate(item)) return item;

            return null;
        }

        public static void ForEach<T>(this IList<T> list, Action<T> action)
        {
            foreach (var item in list)
                action(item);
        }

        public static void InsertAtIndex(this IList list, object item, int index)
        {            
            List<object> buf = new List<object>() { item };

            while(list.Count != index)
            {
                buf.Add(list[index]);
                list.RemoveAt(index);                
            }            

            for (int i = 0; i < buf.Count; i++)
                list.Add(buf[i]);
        }

        public static void InsertAtIndex<T>(this IList<T> list, T item, int index)
        {            
            List<T> buf = new List<T>() { item };

            while (list.Count != index)
            {
                buf.Add(list[index]);
                list.RemoveAt(index);
            }

            for (int i = 0; i < buf.Count; i++)
                list.Add(buf[i]);
        }

        public static IEnumerable<T> Cast<T>(this IList<T> list)
        {
            List<T> result = new List<T>();
            foreach (var item in list)
                result.Add(item);
            return result;
        }
    }
}
